<template>
  <div>
    <!-- 用户登录状态栏 -->
    <div class="user-status-bar">
      <template v-if="userStore.isLoggedIn">
        <span class="username"> {{ userStore.username }}</span>
        <button class="logout-btn" @click="logout">退出</button>
      </template>
      <template v-else>
        <button class="login-btn" @click="goToLogin">登录</button>
      </template>
    </div>
    <div class="movie-list-container">
      <!-- 轮播图区域（Element Plus） -->
      <el-carousel v-if="movies.length > 0" height="320px" :interval="4000" arrow="hover" indicator-position="outside" class="movie-carousel-el">
        <el-carousel-item v-for="movie in movies.slice(0, 6)" :key="movie.id">
          <div class="el-carousel-slide" @click="goToDetail(movie.id)">
            <img :src="movie.imageUrl" class="carousel-img" alt="movie image" />
            <div class="el-carousel-mask">
              <div class="el-carousel-title">{{ movie.title }}</div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
      <h1 class="page-title">电影列表</h1>
      <div class="search-bar">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索电影标题或演员..."
          @keyup.enter="fetchMovies"
        />
        <button @click="fetchMovies">搜索</button>
        <button @click="goToAddMovie" class="add-movie-button">增添电影</button>
      </div>

      <div v-if="loading" class="loading-message">加载中...</div>
      <div v-else-if="error" class="error-message">{{ error }}</div>
      <div v-else-if="movies.length === 0" class="no-data-message">没有找到电影。</div>
      <div v-else class="movie-grid">
        <div
          v-for="movie in filteredMovies"
          :key="movie.id"
          class="movie-card"
          @click="goToDetail(movie.id)"
        >
          <img :src="movie.imageUrl" :alt="movie.title" class="movie-image" />
          <div class="movie-info">
            <h2 class="movie-title">{{ movie.title }}</h2>
            <p class="movie-actors">主演: {{ movie.actors }}</p>
            <p class="movie-description">{{ movie.description }}</p>
            <div class="movie-card-footer">
              <p class="movie-time">发布时间: {{ formatTime(movie.addTime) }}</p>
              <button class="delete-button" @click.stop="handleDelete(movie.id)">删除</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed, onUnmounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessageBox, ElMessage } from 'element-plus'; // 导入 ElMessageBox 和 ElMessage

interface Movie {
  id: number;
  title: string;
  actors: string;
  imageUrl: string;
  playUrl: string;
  addTime: string;
  userId: number;
  description: string;
  categoryId: number;
  authorName: string;
}

export default defineComponent({
  name: 'MovieListView',
  setup() {
    const movies = ref<Movie[]>([]);
    const loading = ref(true);
    const error = ref<string | null>(null);
    const searchQuery = ref('');
    const router = useRouter();
    const userStore = useUserStore();

    // 登录、退出逻辑
    const goToLogin = () => {
      router.push('/login');
    };
    const logout = () => {
      userStore.clearUser();
      window.location.reload();
    };

    // 轮播图逻辑（Element Plus 版本无需手动定时器）
    onMounted(() => {
      fetchMovies();
    });

    const fetchMovies = async () => {
      loading.value = true;
      error.value = null;
      try {
        const response = await axios.get('/api/demo/getallitems?typeIndex=3');
        // 假设API返回的是一个直接的数组
        if (Array.isArray(response.data)) {
          movies.value = response.data.map((item: any) => ({
            id: item.id,
            title: item.title,
            actors: item.actors,
            imageUrl: item.picPaths, // 映射 picPaths 到 imageUrl
            playUrl: item.playUrl,
            addTime: item.addedTime, // 映射 addedTime 到 addTime
            userId: item.userid, // 映射 userid 到 userId
            description: item.desc, // 映射 desc 到 description
            categoryId: item.categoryid, // 映射 categoryid 到 categoryId
            authorName: item.authorName,
          }));
        } else {
          error.value = 'API返回数据格式不正确。';
        }
      } catch (err) {
        console.error('获取电影列表失败:', err);
        error.value = '无法加载电影列表。请稍后再试。';
      } finally {
        loading.value = false;
      }
    };

    const handleDelete = async (id: number) => {
      ElMessageBox.confirm('此操作将永久删除该电影, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const response = await axios.post('/api/demo/deleteitem', {
              delid: id,
              typeIndex: 3,
            });
            if (response.data === 'del ok!!!') {
              ElMessage({
                type: 'success',
                message: '删除成功!',
              });
              fetchMovies(); // 删除成功后重新加载列表
            } else {
              ElMessage({
                type: 'error',
                message: '删除失败: ' + response.data,
              });
            }
          } catch (err) {
            console.error('删除电影失败:', err);
            ElMessage({
              type: 'error',
              message: '删除电影失败，请稍后再试。',
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        });
    };

    const filteredMovies = computed(() => {
      if (!searchQuery.value) {
        return movies.value;
      }
      const query = searchQuery.value.toLowerCase();
      return movies.value.filter(
        (movie) =>
          movie.title.toLowerCase().includes(query) ||
          movie.actors.toLowerCase().includes(query)
      );
    });

    const goToDetail = (id: number) => {
      router.push(`/movie/${id}`);
    };

    const goToAddMovie = () => {
      router.push('/add-movie');
    };

    const formatTime = (timeString: string) => {
      const date = new Date(timeString);
      return date.toLocaleString(); // 格式化日期时间
    };


    onMounted(() => {
      fetchMovies();
    });

    return {
      movies,
      loading,
      error,
      searchQuery,
      filteredMovies,
      fetchMovies,
      goToDetail,
      goToAddMovie, // 暴露 goToAddMovie 方法
      formatTime,
      userStore,
      goToLogin,
      logout,
      handleDelete, // 暴露 handleDelete 方法
    };
  },
});
</script>
/* Element Plus 轮播图美化 */
.movie-carousel-el {
  margin-bottom: 32px;
}

.el-carousel-slide {
  width: 100%;
  height: 320px;
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(60, 80, 120, 0.13);
  position: relative;
  cursor: pointer;
  display: flex;
  align-items: flex-end;
  overflow: hidden;
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  border-radius: 0;
}
.el-carousel-mask {
  width: 100%;
  background: linear-gradient(180deg, rgba(0,0,0,0) 60%, rgba(0,0,0,0.45) 100%);
  padding: 0 0 32px 0;
  border-radius: 0 0 18px 18px;
  display: flex;
  position: relative;
  z-index: 1;
  align-items: flex-end;
}
.el-carousel-title {
  color: #fff;
  font-size: 2em;
  font-weight: 700;
  padding: 0 32px 0 24px;
  text-shadow: 0 2px 12px rgba(0,0,0,0.18);
  letter-spacing: 2px;

  position: relative;
  z-index: 2;
  line-height: 1.2;

}
@media (max-width: 900px) {
  .el-carousel-slide { height: 180px; }
  .el-carousel-title { font-size: 1.1em; padding: 0 12px 0 12px; }
  .el-carousel-mask { padding-bottom: 16px; }
}

<style scoped>
.user-status-bar {
  position: sticky;
  top: 0;
  z-index: 20;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 18px;
  background: linear-gradient(90deg, #f8fafc 0%, #e0f7fa 100%);
  border-radius: 0 0 18px 18px;
  box-shadow: 0 2px 12px rgba(60, 80, 120, 0.08);
  padding: 14px 40px 12px 40px;
  margin-bottom: 16px;
}
.user-status-bar .username {
  font-size: 1.13em;
  color: #1e88e5;
  font-weight: 700;
  margin-right: 10px;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #b2ebf2 0%, #90caf9 100%);
  padding: 4px 16px 4px 12px;
  border-radius: 16px;
  box-shadow: 0 1px 6px rgba(30,136,229,0.07);
  display: flex;
  align-items: center;
}
.user-status-bar .username::before {
  content: '👤';
  margin-right: 6px;
  font-size: 1.1em;
}
.user-status-bar .login-btn {
  background: #e3f2fd;
  color: #1976d2;
  font-weight: 600;
  border: 1.5px solid #b3e5fc;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.07);
  padding: 8px 26px;
  border-radius: 20px;
  transition: background 0.2s, color 0.2s, border 0.2s;
}
.user-status-bar .login-btn:hover {
  background: #bbdefb;
  color: #0d47a1;
  border-color: #90caf9;
}
.user-status-bar .logout-btn {
  background: #fff3e0;
  color: #d84315;
  font-weight: 600;
  border: 1.5px solid #ffccbc;
  box-shadow: 0 2px 8px rgba(216, 67, 21, 0.07);
  padding: 8px 26px;
  border-radius: 20px;
  transition: background 0.2s, color 0.2s, border 0.2s;
}
.user-status-bar .logout-btn:hover {
  background: #ffe0b2;
  color: #b71c1c;
  border-color: #ffab91;
}
.movie-list-container {
  padding: 24px 16px;
  max-width: 1200px;
  margin: 28px auto;
  font-family: 'Segoe UI', 'Arial', sans-serif;
  color: #222;
  background: linear-gradient(135deg, #f8fafc 60%, #e3e9f0 100%);
  border-radius: 18px;
  box-shadow: 0 6px 32px 0 rgba(60, 80, 120, 0.13);
}

.page-title {
  text-align: center;
  color: #1a2233;
  margin-bottom: 36px;
  font-size: 2.7em;
  font-weight: 700;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(60, 80, 120, 0.08);
}

.search-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 36px;
  gap: 14px;
  background: #fff;
  border-radius: 32px;
  box-shadow: 0 2px 12px rgba(60, 80, 120, 0.07);
  padding: 10px 18px;
}

.search-bar input {
  width: 320px;
  max-width: 60vw;
  padding: 13px 22px;
  border: none;
  border-radius: 24px;
  font-size: 1.08em;
  background: #f3f6fa;
  outline: none;
  transition: box-shadow 0.3s, background 0.3s;
  box-shadow: 0 1px 4px rgba(60, 80, 120, 0.04) inset;
}

.search-bar input:focus {
  background: #eaf2fb;
  box-shadow: 0 0 0 2px #7bb6fa;
}

.search-bar button {
  padding: 12px 28px;
  background: linear-gradient(90deg, #4f8cff 60%, #1e6be3 100%);
  color: #fff;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-size: 1.05em;
  font-weight: 500;
  letter-spacing: 1px;
  transition: background 0.25s, transform 0.18s, box-shadow 0.18s;
  box-shadow: 0 2px 8px rgba(60, 80, 120, 0.10);
}

.search-bar button:hover {
  background: linear-gradient(90deg, #3576e0 60%, #1e6be3 100%);
  transform: translateY(-2px) scale(1.04);
  box-shadow: 0 4px 16px rgba(60, 80, 120, 0.13);
}

.search-bar button:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(60, 80, 120, 0.08);
}

.add-movie-button {
  background: linear-gradient(90deg, #34d399 60%, #059669 100%);
  color: #fff;
  border: none;
  border-radius: 24px;
  font-size: 1.05em;
  font-weight: 500;
  padding: 12px 28px;
  margin-left: 4px;
  cursor: pointer;
  transition: background 0.25s, transform 0.18s, box-shadow 0.18s;
  box-shadow: 0 2px 8px rgba(52, 211, 153, 0.10);
}

.add-movie-button:hover {
  background: linear-gradient(90deg, #059669 60%, #34d399 100%);
  transform: translateY(-2px) scale(1.04);
  box-shadow: 0 4px 16px rgba(52, 211, 153, 0.13);
}

.add-movie-button:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(52, 211, 153, 0.08);
}

.loading-message,
.error-message,
.no-data-message {
  text-align: center;
  font-size: 1.13em;
  color: #666;
  margin-top: 24px;
}

.error-message {
  color: #e74c3c;
}

.movie-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 28px;
  justify-content: center;
}

.movie-card {
  background: linear-gradient(135deg, #fafdff 70%, #e3e9f0 100%);
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(60, 80, 120, 0.13);
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.22s cubic-bezier(.4,1.3,.6,1), box-shadow 0.22s;
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1.5px solid #e3e9f0;
  position: relative;
}

.movie-card:hover {
  transform: translateY(-8px) scale(1.025);
  box-shadow: 0 8px 32px rgba(60, 80, 120, 0.18);
  border-color: #7bb6fa;
}

.movie-image {
  width: 100%;
  height: 320px;
  object-fit: cover;
  border-bottom: 1.5px solid #e3e9f0;
  background: #f3f6fa;
  transition: filter 0.2s;
}

.movie-card:hover .movie-image {
  filter: brightness(1.04) saturate(1.08);
}

.movie-info {
  padding: 18px 16px 14px 16px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background: transparent;
  position: relative; /* 确保相对定位，以便内部元素可以绝对定位 */
}

.movie-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto; /* 将 footer 推到底部 */
  width: 100%;
}

.movie-time {
  font-size: 0.89em;
  color: #888;
  text-align: left; /* 确保发布时间靠左 */
  font-style: italic;
  margin-top: 0; /* 移除默认的上边距 */
}

.delete-button {
  /* 调整删除按钮的定位，使其不再与发布时间重叠 */
  position: static; /* 将定位改为静态，使其参与flex布局 */
  background-color: #f44336; /* 红色背景 */
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 0.9em;
  transition: background-color 0.3s ease;
}

.delete-button:hover {
  background-color: #d32f2f; /* 深红色 */
}

.movie-title {
  font-size: 1.22em;
  font-weight: 700;
  color: #1a2233;
  margin-bottom: 7px;
  line-height: 1.3;
  letter-spacing: 1px;
  text-shadow: 0 1px 4px rgba(60, 80, 120, 0.06);
}

.movie-actors {
  font-size: 0.98em;
  color: #3b82f6;
  margin-bottom: 6px;
  font-weight: 500;
}

.movie-description {
  font-size: 0.97em;
  color: #444;
  line-height: 1.5;
  margin-bottom: 12px;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.movie-time {
  font-size: 0.89em;
  color: #888;
  text-align: right;
  margin-top: auto;
  font-style: italic;
}

/* 响应式调整 */
@media (max-width: 900px) {
  .movie-list-container {
    padding: 12px 2vw;
    margin: 10px auto;
  }
  .page-title {
    font-size: 2em;
  }
  .search-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
    padding: 10px 6px;
  }
  .search-bar input {
    width: 100%;
    max-width: 100%;
  }
  .search-bar button {
    width: 100%;
  }
  .movie-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 16px;
  }
  .movie-image {
    height: 180px;
  }
  .movie-title {
    font-size: 1.08em;
  }
  .movie-description {
    -webkit-line-clamp: 2;
  }
}
</style>